package com.demo.function.spring.spel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.math.BigDecimal;

/**
 * 使用SpringEL表达式进行比较
 */
@Slf4j
public class CompareEl {

    // 创建解析器
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    public static void main(String[] args) {
        compareInteger();
        compareBigDecimal();
    }

    private static void compareInteger() {
        Expression expression = PARSER.parseExpression("#value1 == #value2");

        //设置解析上下文(有哪些占位荷,以及每种占位符的值-根据方法的参数名和参数值
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("value1", 1);
        context.setVariable("value2", 2);

        Boolean flag = expression.getValue(context, Boolean.class);
        log.info("Integer el表达式比较:{}", flag);
    }

    private static void compareBigDecimal() {

        BigDecimal value1 = new BigDecimal("1.0");
        BigDecimal value2 = new BigDecimal("2.0");

        Expression expression = PARSER.parseExpression("#value1.compareTo(new java.math.BigDecimal(#value2))");

        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("value1", value1);
        context.setVariable("value2", value2);

        Integer flag = expression.getValue(context, Integer.class);
        log.info("BigDecimal el表达式比较：{}", flag);
    }
}
